package com.ml.view;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.ml.app.MyApplication;
import com.ml.tools.BaseActivity;
import com.ml.tools.Config;
import com.ml.tools.Utils;
import com.ml.version.UpdateManager;

import org.json.JSONArray;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;

public class LoginActivity extends BaseActivity {
    RequestQueue mQueue = null;
    JsonObjectRequest mJsonObjectRequest = null;
    String riqi = "";
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    private EditText et_user, et_pwd;
    private TextView title_tv, tv_right_btn;
    private Button tv_commit;
    private String userurl = MyApplication.SERVERPATH + "/Y502/Pad2Login";
    private String username, password;
    private String linename, sn, renshu, k1, k2, k3, j1, j2, j3, mbcl, mbpph, jiepai, taitou, po;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onResume() {
        super.onResume();
        userurl = MyApplication.SERVERPATH + "/Y502/Pad2Login";
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        mQueue = MyApplication.getRequestQueue();
        username = MyApplication.getSharedUserInfo().getString("username", "admin");
        password = MyApplication.getSharedUserInfo().getString("password", "123");
        riqi = MyApplication.getSharedUserInfo().getString("riqi", "");

        initView();
        MyApplication.getSharedUserInfo().edit().putString(Config.ACCESS_TOKEN, "").commit();

        //apk版本升级
        UpdateManager.getUpdateManager().checkAppUpdate(this, false);

        new Thread() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    time++;
                    if (time > 6) {
                        mHandler.sendEmptyMessage(ONMAIN);
                        break;
                    }
                }
            }
        }.start();

//        Intent intent = new Intent(this, MyService.class);
//        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
//            //适配8.0机制
//            context.startForegroundService(intent);
//        } else {
//            context.startService(intent);
//        }
    }

    int time = 0;
    public static final int ONMAIN = 1313;//到首页

    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (ONMAIN == msg.what) {
                onMain();
            }
        }
    };

    private void initView() {
        et_user = (EditText) findViewById(R.id.et_user);
        et_user.setText(username);
        et_user.setHint(MyApplication.map.get("input_username"));
        et_pwd = (EditText) findViewById(R.id.et_pwd);
        et_pwd.setTypeface(Typeface.DEFAULT);
        et_pwd.setTransformationMethod(new PasswordTransformationMethod());
        et_pwd.setText(password);
        et_pwd.setHint(MyApplication.map.get("input_password"));
        title_tv = (TextView) findViewById(R.id.title_tv);
        title_tv.setText(MyApplication.map.get("Easement"));
        tv_commit = (Button) findViewById(R.id.tv_commit);
        tv_commit.setOnClickListener(this);
        tv_commit.setText(MyApplication.map.get("login"));
        tv_right_btn = (TextView) findViewById(R.id.tv_right_btn);
        tv_right_btn.setText(MyApplication.map.get("networksetting"));
        tv_right_btn.setOnClickListener(this);
        et_user.setFocusable(true);
        et_user.setFocusableInTouchMode(true);
        //et_user.seth               //set HInt
        et_pwd.setFocusable(true);
        et_pwd.setFocusableInTouchMode(true);
        tv_right_btn.setFocusable(true);
        tv_right_btn.setFocusableInTouchMode(true);
        tv_commit.setFocusable(true);
        tv_commit.setFocusableInTouchMode(true);
    }

    void onMain() {
        if (MyApplication.getServersInfo().getString("serverip", "").equals("")) {
            showToast(MyApplication.map.get("input_ipport"));
            return;
        }
        username = et_user.getText().toString();
        if (username.trim().equals("")) {
            showToast(MyApplication.map.get("input_username"));
            return;
        }
        password = et_pwd.getText().toString();
        if (password.trim().equals("")) {
            showToast(MyApplication.map.get("input_password"));
            return;
        }
        login(username, password);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_commit:
                onMain();
                break;
            case R.id.tv_right_btn:
                time = -20000;
                startActivity(new Intent(this, NetSettingActivity.class));
                break;
            default:
                break;
        }
    }

    private void login(String name, String pass) {

        boolean isConnected = Utils.toastIsNetworkConnected(context);
        if (isConnected) {
            showProgressBar();
            String url = userurl + "?name=" + name + "&&pass=" + pass;
            //RequestQueue mQueue = Volley.newRequestQueue(getApplicationContext());
            mJsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url,
                    null, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    hideProgressBar();
                    parseData(response);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    hideProgressBar();
                    showToast(MyApplication.map.get("network_error_try_again"));
                }
            }
            );
            mQueue.add(mJsonObjectRequest);
        } else {
            showToast(MyApplication.map.get("network_error_try_again"));
            return;
        }
    }

    @Override
    protected void onDestroy() {
//	MyApplication.mylist.remove(this);
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void parseData(JSONObject response) {

        String access_token = "access_token";
        String result = response.optString("result");
        if (result == null || result.equals("") || result.equals("fail")) {
            MyApplication.getSharedUserInfo().edit().putString(Config.ACCESS_TOKEN, "").commit();
            MyApplication.getSharedUserInfo().edit().putString("password", "").commit();
            showToast(R.string.login_error);
            return;
        }
        MyApplication.getSharedUserInfo().edit().putString(Config.ACCESS_TOKEN, access_token).commit();
        MyApplication.getSharedUserInfo().edit().putString("username", username).commit();
        MyApplication.getSharedUserInfo().edit().putString("password", password).commit();
        JSONArray array = response.optJSONArray("data");
        if (array != null) {
            JSONObject obj = array.optJSONObject(0);  // linename,sn,renshu,k1,k2,k3,j1,j2,j3;
            linename = obj.optString("linename");
            sn = obj.optString("sn");
            MyApplication.sn = sn;
            renshu = obj.optString("renshu");
            k1 = obj.optString("k1");
            k2 = obj.optString("k2");
            k3 = obj.optString("k3");
            j1 = obj.optString("j1");
            j2 = obj.optString("j2");
            j3 = obj.optString("j3");
            mbcl = obj.optString("mbcl");
            mbpph = obj.optString("mbpph");
            jiepai = obj.optString("jiepai");
            taitou = obj.optString("taitou");
            MyApplication.taitou = taitou;
            riqi = obj.optString("riqi");
            MyApplication.riqi = riqi;
            po = obj.optString("modeltext");
        }

        Long stime = response.optLong("time", 0);
        if (stime > 0) {
            long now = System.currentTimeMillis() / 1000; //当前时间
            long xtime = stime - now;
            if (xtime > 60 || xtime < -60) {
                MyApplication.xtime = xtime;
            }
        }
        long thistime = MyApplication.xtime * 1000 + System.currentTimeMillis();

        String riqi1 = df.format(new Date(thistime));
        if (!riqi1.equals(riqi)) {
            MyApplication.getSharedUserInfo().edit().putString("nnn", "0").commit();
            MyApplication.getSharedUserInfo().edit().putString("riqi", riqi1).commit();
        }

        Intent intent = new Intent(this, MainActivity2.class); //MyChapo
        intent.putExtra("linename", linename);
        intent.putExtra("sn", sn);
        intent.putExtra("k1", k1);
        intent.putExtra("k2", k2);
        intent.putExtra("k3", k3);
        intent.putExtra("j1", j1);
        intent.putExtra("j2", j2);
        intent.putExtra("j3", j3);
        intent.putExtra("po", po);
        intent.putExtra("renshu", renshu);
        intent.putExtra("mbcl", mbcl);
        intent.putExtra("mbpph", mbpph);
        intent.putExtra("jiepai", jiepai);
        intent.putExtra("taitou", taitou);
        intent.putExtra("riqi", riqi);
        startActivity(intent);
        finish();
    }


}
